package com.backend.demo1.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.backend.demo1.mapper.ArticleMapper;
import com.backend.demo1.utils.RedisUtils;

@Service
public class SyncService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ArticleMapper articleMapper;

    // 每隔 5 分钟执行一次同步任务
    @Scheduled(cron = "0 */5 * * * ?")
    public void syncLikesToDatabase() {
        try {
            // 获取所有需要同步的公告 ID（可以根据业务需求调整）
            List<String> articleIds = articleMapper.findAllArticleIds();

            for (String id : articleIds) {
                // 从 Redis 获取点赞数
                int likeCount = redisUtils.getLikeCount(id);

                // 更新到 MySQL 数据库
                articleMapper.updateLikeCount(id, likeCount);
            }
        } catch (Exception e) {
            // 记录同步失败日志
            System.err.println("同步点赞数失败: " + e.getMessage());
        }
    }
}